<?php
declare (strict_types = 1);
namespace app\api\controller;

use \Firebase\JWT\JWT;
use think\exception\HttpResponseException;
use think\Response;
use think\facade\{Db};

class PublicController
{
    /**
     * 生成token
     * @param int $user_id 用户id
     * @return string
     */
    public function jwt($user_id)
    {
        $key = config('api.jwt');

        $data = [
            "iss"     => "qingze",
            "aud"     => "qingze",
            'user_id' => $user_id
        ];

        return JWT::encode($data, $key);
    }
    
    public function success_back($msg = '', $data = [], $code = 200, $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
        ];
    
        $response = Response::create($result, 'json')->header($header);
        throw new HttpResponseException($response);
    }

    public function error_back($msg = '', $data = [], $code = 400, $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
        ];
    
        $response = Response::create($result, 'json')->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 开启事务
     */
    public static function beginTrans()
    {
        Db::startTrans();
    }

    /**
     * 提交事务
     */
    public static function commitTrans()
    {
        Db::commit();
    }

    /**
     * 回滚事务
     */
    public static function rollbackTrans()
    {
        Db::rollback();
    }
}